package com.liam.leetcode;

/**
 *  3

 0  2   4   6                                   2n - 2
 1  3   5   7                                   2n - 1


 0      4       8       12                       4n - 4
 1  3   5   7   9   11  13  15                   2n - 1
 2      6       10      14                       4n - 2


 0          6           12                       6n - 6
 1      5   7       11  13                       2n - 1       258
 2  4       8   10      14                       2n           359
 3          9           15                       6n - 3


 0              8               16              8n - 8
 1          7   9           15                  2n - 1      2367
 2      6       10      14                      2n
 3  5           11  13                          2n - 1      n>1
 4              12                              8n - 4



 0                  10                  20
 1              9   11              19
 2          8       12          18
 3      7           13      17
 4  6               14  16
 5                  15



    0   2   4   6   8

 第0行：       (2k-2)n - (2k-2)      (2k-2)(n-1)
 第i 奇数行     2n-1    n>=(i+1)/2
    偶数行     2n       n>=i/2

 最后一行       (2k-2)n - (k-1)


 *
 */

public class Z字形变_6 {

    public static void main(String[] args) {
        String s = "LEETCODEISHIRING";
        System.out.println(convert(s,3));

//        int [] [] result = new int[3][9];
//        for(int i=0;i<result.length;i++){
//            for(int j=0;j<result[i].length;j++){
//                System.out.print(i+","+j+";");
//            }
//            System.out.println();
//        }
    }


    public static  String convert(String s, int numRows) {
        if(numRows == 1){
            return s;
        }
        Integer [] [] result = new Integer[numRows][s.length()/2 + 1];

        boolean isDown = true;
        int x = 0;
        int y = 0;
        for (int i=0;i<s.length() ;i++){
            if(isDown){
//                System.out.println(x+","+y+" 内容："+i +" isDown:"+isDown);
                result[y][x] = i;
                y ++ ;
            }else{
                x ++ ;
                y -- ;
//                System.out.println(x+","+y+" 内容："+i +" isDown:"+isDown);
                result[y][x] = i;
            }
            if(y==numRows || y==0){
                if(y == 0 ){
                    y ++;
                }else{
                    y --;
                }
                isDown = !isDown;
            }

        }
        StringBuffer sb = new StringBuffer();
        for(int i=0;i<result.length;i++){
            for(int j=0;j<result[i].length;j++){
                if(result[i][j] != null){
                    sb.append(s.charAt(result[i][j]));
                }
            }
        }
        return sb.toString();

    }
}
